package com.mysql.study.service;

import com.mysql.study.Dao.UserDao;
import com.mysql.study.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    /**
     * 利用主键ID删除数据
     * @param id
     */
    @Transactional
    public void deleteUserById(Integer id){
        this.userDao.deleteByPrimaryKey(id);
    }

    /**
     *利用ID找到指定用户
     * @param id
     * @return
     */
    @Transactional
    public User EditUserById(Integer id){
       return this.userDao.selectByPrimaryKey(id);
    }

    @Transactional
    public int EditUser(User user,String pwd){
        System.out.println(user.getUserId());
        if(user.getPassword().equals(pwd)){
            this.userDao.updateByPrimaryKey(user);
            return 1;
        }
        return 0;
    }
    /**
     * 查询所有数据
     * @return
     */
    @Transactional
    public List<User> UserAll(){
        return this.userDao.selectAll();
    }

    /**
     * 从数据库中验证用户,如果数据库中没有为0,有且等于root则为1,有没有root则为2
     * @param user
     * @return
     */
    @Transactional
    public User loginUser(User user){
        if(user.getEmail() == null) {
            return this.userDao.selectLogin(user);
        }else{
            System.out.println("email login");
            return this.userDao.selectLoginmail(user.getEmail());
        }
    }
    @Transactional
    public User emaillogin(User user){
        User user1 = this.userDao.selectLoginmail(user.getEmail());
        System.out.println(user1.getNickName());
        return user1;
    }

    /**
     * 添加用户
     * @param user
     * @param pwd
     * @return
     */
    @Transactional
    public int addUser(User user, String pwd){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date = df.format(new Date());
        user.setLastLoginTime(date);
        if(user.getPassword().equals(pwd)){
            return this.userDao.insert(user);
        }
       return 0;
    }

    /**
     * 查询
     * @param content
     * @return
     */
    @Transactional
    public List<User> FindQuery(String content){
        return this.userDao.selectByQuery(content);
    }
}
